package com.hqyj.realm;

import com.hqyj.dao.UserMapper;
import com.hqyj.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @Description
 * @Autor 伍军
 * @Date 2021/10/12 10:10
 * @Version 1.0
 **/
public class MyRealm extends AuthorizingRealm {
    @Autowired(required = false)
    UserMapper userMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    //认证(登录)
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //取出用户名
        UsernamePasswordToken to = (UsernamePasswordToken) token;
        String userName = to.getPrincipal() + "";
        //验证用户名输入是否正确
        System.out.println(userName);
        List<User> list = userMapper.selectByName(userName);
        if (list.size() == 0) {
            throw new UnknownAccountException();
        }
        //创建凭证
        AuthenticationInfo au = new SimpleAuthenticationInfo(
                list.get(0).getUserName(),//用户名
                list.get(0).getPassWord(),
                new Md5Hash(list.get(0).getSalt()),//加密算法和盐值
                this.getName()//myrealm对象
        );
        return au;
    }
}
